import { useState, useEffect, useRef } from 'react';
import { groupBy, orderBy } from 'lodash';
import Uncheck from './UnCheck';
import UnShip from './UnShip';
import Shiped from './Shiped';
import Canceled from './Canceled';
import { kuaiXiaoPrintFunc } from '@/utils/print.jsx';
import Api from '../service';

//打印数据处理
const formatPrintOrder = (val) => {
	const printArr = [];
	const arr = orderBy(val, 'printSequence');
	const list = groupBy(arr, 'warehouseId');
	for(let i in list) {
		const list1 = groupBy(list[i], 'printer');
		for(let j in list1) {
			const list2 = list1[j];
			list2.map((v, index) => {
				printArr.push({
					...v,
					num: index + 1,
					len: list2.length,
				})
			})
		}
	}
	return printArr;
}

//打单发货的操作
const OrderShip = (props) => {
	const { searchForm, orderList: pageData } = props;
	const { pageType } = searchForm;

	// 当前打印的面单数据列表
	const [orderList, setOrderList] = useState([]);
	const isPrint = useRef(false);
	const storageData = useRef([]);
	const pointer = useRef(0);

	useEffect(()=>{
   if(orderList?.length){
		pointer.current = 0;
		executePrintFunc();
	 }
	
	}, [orderList])

const executePrintFunc = () => {
	const promise = new Promise(resolve=>{
		if(pointer.current == orderList?.length){
     return resolve()
		}
		kuaiXiaoPrintFunc(orderList[pointer.current], (res)=>{
			const { status, logPage, printTaskId, orderSn } = res;
      if(status){
        Api.printSuccessOp({ 
					logPage, 
					printTaskId, 
					systemNos: [orderSn] 
				});
			}
			pointer.current++;
			executePrintFunc();
		})
	})

	promise.then(()=>{
		const awaitArr = storageData.current;
		console.log(awaitArr,'awaitArr')
		if(awaitArr.length){
			setOrderList(awaitArr[0]);
			awaitArr.splice(0, 1);
		}else{
			isPrint.current = false;
			setOrderList([]);
		}
	})
}

	const enhanceProps = {
		...props,
		handleSavaPrint(val){
			const arr = formatPrintOrder(val);
			console.log(arr, 'arr')
			if(isPrint.current){
				console.log('暂存')
				storageData.current.push(arr);
			}else{
				isPrint.current = true;
				setOrderList(arr);
			}
		}
	}

	switch(pageType) {
		case '1' : {
			return <Uncheck { ...props } /> 
		}
		case '2' : {
			return <UnShip { ...enhanceProps } /> 
		}
		case '3' : {
			return <Shiped { ...enhanceProps } /> 
		}
		case '4' : {
			return <Canceled { ...props } /> 
		}
		default : {
			return null;
		}
	}
}

export default OrderShip;